package com.iotimc.attendancesystem.util;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.support.annotation.FloatRange;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.gifdecoder.GifDecoder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.bumptech.glide.request.target.Target;
import com.iotimc.attendancesystem.R;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.math.BigDecimal;
import java.util.concurrent.ExecutionException;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


/**
 * @author cwj
 *         Created by cwj
 *         <p>
 *         <p>
 *         recyclerView中使用Glide框架，内存剧增或者爆内存溢出（OutOfMemoryError）,原因：在ImageView中scaleType使用了fitxy属性
 *         注意：使用了transform以后，就不能使用centercrop，fitcenter等方法
 *         <p>
 *         为了避免Glide自动把bitmap放大，使用在加载图片的时候，使用 .override(width, height) 限制图片的宽高
 *         <p>
 *         java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
 *         使用的时候，需要先判断activity.isFinish()
 *         <p>
 *         加载bitmap图的时候加上.asBitmap()
 *         <p>
 *         不要再非主线程里面使用Glide加载图片，如果真的使用了，请把context参数换成getApplicationContext
 *         <p>
 *         OkHttp集成
 *         compile 'com.github.bumptech.glide:okhttp3-integration:1.4.0@aar'
 *         new OkHttpClient.Builder()
 *         .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
 *         .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
 *         .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
 *         .build();
 */


public class PictureManager {

    private final int PLACEHOLDER = R.drawable.ic_user_img;
    private final int ERROR = R.drawable.ic_user_img;
    private final int PLACEHOLDER_CIRCLE = R.drawable.ic_user_img;
    private final int ERROR_CIRCLE = R.drawable.ic_user_img;
    private static PictureManager mManager;
    private static RequestListener<Object, GlideDrawable> bitmapListener;
    private static RequestListener<Object, GifDrawable> gifListener;


    public static PictureManager getInstance() {
        if (mManager != null) {
            return mManager;
        }

        //设置图片加载监听
        bitmapListener = new RequestListener<Object, GlideDrawable>() {
            @Override
            public boolean onException(Exception e, Object model, Target<GlideDrawable> target, boolean isFirstResource) {
                Log.e("PictureManager", "onException------>" + (e == null ? "" : e.toString()) + "------>isFirstResource: " + isFirstResource + "------>model:" + model);
                return false;
            }

            @Override
            public boolean onResourceReady(GlideDrawable resource, Object model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                Log.i("PictureManager", "onResourceReady------>" + "isFromMemoryCache:" + isFromMemoryCache + "------>isFirstResource: " + isFirstResource + "------>model:" + model);
                return false;
            }
        };

        gifListener = new RequestListener<Object, GifDrawable>() {
            @Override
            public boolean onException(Exception e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
                Log.e("PictureManager", "onException------>" + (e == null ? "" : e.toString()) + "------>isFirstResource: " + isFirstResource + "------>model:" + model);
                return false;
            }

            @Override
            public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                Log.i("PictureManager", "onResourceReady------>" + "isFromMemoryCache:" + isFromMemoryCache + "------>isFirstResource: " + isFirstResource + "------>model:" + model);
                return false;
            }
        };

        return mManager = new PictureManager();
    }

    /**
     * 图片的加载
     *
     * @param context context
     * @param src     String/uri/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */
    public void load(Context context, String src, ImageView view, boolean cache) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .priority(Priority.NORMAL)
                   // .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                  //  .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        }
    }

    public void load(Context context, Uri src, ImageView view, boolean cache) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .priority(Priority.NORMAL)
                    //.placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    //.placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        }
    }

    public void load(Context context, byte[] src, ImageView view, boolean cache) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .priority(Priority.NORMAL)
                    //.placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                   // .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        }
    }


    public void load(Context context, File src, ImageView view, boolean cache) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .priority(Priority.NORMAL)
                    //.placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                   // .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        }
    }


    public void load(Context context, Integer src, ImageView view, boolean cache) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .priority(Priority.NORMAL)
                    //.placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                   // .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        }
    }

    public <T> void load(Context context, T src, ImageView view, boolean cache) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .priority(Priority.NORMAL)
                    //.placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    //.placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        }
    }


    /**
     * 圆形图片
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */

    public void loadCirclePic(final Context context, Object src, ImageView view, boolean cache) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new CircleTransform(context))
                    .placeholder(PLACEHOLDER_CIRCLE)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new CircleTransform(context))
                    .placeholder(PLACEHOLDER_CIRCLE)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)
                    .into(view);

        }
    }

    /**
     * 圆形图片
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */

    public void loadCirclePic(final Context context, String src, ImageView view, boolean cache) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new CircleTransform(context))
                    .placeholder(PLACEHOLDER_CIRCLE)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new CircleTransform(context))
                    .placeholder(PLACEHOLDER_CIRCLE)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)
                    .into(view);

        }
    }

    /**
     * 圆形图片
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */

    public void loadCirclePic(final Context context, Uri src, ImageView view, boolean cache) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new CircleTransform(context))
                    .placeholder(PLACEHOLDER_CIRCLE)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new CircleTransform(context))
                    .placeholder(PLACEHOLDER_CIRCLE)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)
                    .into(view);

        }
    }

    /**
     * 圆形图片
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */

    public void loadCirclePic(final Context context, Integer src, ImageView view, boolean cache) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new CircleTransform(context))
                    .placeholder(PLACEHOLDER_CIRCLE)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new CircleTransform(context))
                    .placeholder(PLACEHOLDER_CIRCLE)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)
                    .into(view);

        }
    }

    /**
     * 圆形图片
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */

    public void loadCirclePic(final Context context, File src, ImageView view, boolean cache) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new CircleTransform(context))
                    .placeholder(PLACEHOLDER_CIRCLE)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new CircleTransform(context))
                    .placeholder(PLACEHOLDER_CIRCLE)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)
                    .into(view);

        }
    }

    /**
     * 圆形图片
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */

    public void loadCirclePic(final Context context, byte[] src, ImageView view, boolean cache) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new CircleTransform(context))
                    .placeholder(PLACEHOLDER_CIRCLE)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new CircleTransform(context))
                    .placeholder(PLACEHOLDER_CIRCLE)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)
                    .into(view);

        }
    }

    private class CircleTransform extends BitmapTransformation {
        CircleTransform(Context context) {
            super(context);
        }

        @Override
        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            return circleCrop(pool, toTransform);
        }

        private Bitmap circleCrop(BitmapPool pool, Bitmap source) {
            if (source == null) {
                return null;
            }

            int size = Math.min(source.getWidth(), source.getHeight());
            int x = (source.getWidth() - size) / 2;
            int y = (source.getHeight() - size) / 2;

            Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);

            Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
            if (result == null) {
                result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
            }

            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
            paint.setAntiAlias(true);
            float r = size / 2f;
            canvas.drawCircle(r, r, r, paint);
            return result;
        }

        @Override
        public String getId() {
            return getClass().getName();
        }
    }


    /**
     * 圆角图片
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */
    public void loadRoundPic(Context context, Object src, ImageView view, boolean cache, int radio) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new GlideRoundTransform(context, radio))
                    .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new GlideRoundTransform(context, radio))
                    .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);

        }
    }

    /**
     * 圆角图片
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */
    public void loadRoundPic(Context context, String src, ImageView view, boolean cache, int radio) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new GlideRoundTransform(context, radio))
                    .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new GlideRoundTransform(context, radio))
                    .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);

        }
    }

    /**
     * 圆角图片
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */
    public void loadRoundPic(Context context, Uri src, ImageView view, boolean cache, int radio) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new GlideRoundTransform(context, radio))
                    .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new GlideRoundTransform(context, radio))
                    .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);

        }
    }

    /**
     * 圆角图片
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */
    public void loadRoundPic(Context context, Integer src, ImageView view, boolean cache, int radio) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new GlideRoundTransform(context, radio))
                    .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new GlideRoundTransform(context, radio))
                    .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);

        }
    }

    /**
     * 圆角图片
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */
    public void loadRoundPic(Context context, File src, ImageView view, boolean cache, int radio) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new GlideRoundTransform(context, radio))
                    .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new GlideRoundTransform(context, radio))
                    .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);

        }
    }


    /**
     * 圆角图片
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */
    public void loadRoundPic(Context context, byte[] src, ImageView view, boolean cache, int radio) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new GlideRoundTransform(context, radio))
                    .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new GlideRoundTransform(context, radio))
                    .placeholder(PLACEHOLDER)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);

        }
    }


    private class GlideRoundTransform extends BitmapTransformation {

        private float radius = 0f;

        GlideRoundTransform(Context context, int dp) {
            super(context);
            radius = Resources.getSystem().getDisplayMetrics().density * dp;
        }

        @Override
        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            return roundCrop(pool, toTransform);
        }

        private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
            if (source == null) {
                return null;
            }
            Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            if (result == null) {
                result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            }

            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
            paint.setAntiAlias(true);
            RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
            canvas.drawRoundRect(rectF, radius, radius, paint);
            return result;
        }

        @Override
        public String getId() {
            return getClass().getName() + Math.round(radius);
        }
    }


    /**
     * 加载gif图片
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     */
    public void loadGif(Context context, Object src, ImageView view, int count) {
        if (context == null || view == null) {
            return;
        }
        if (count < 1) {
            Glide.with(context)
                    .load(src)
                    .asGif()
                    .listener(gifListener)
                    .centerCrop()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .priority(Priority.NORMAL)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR)
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .centerCrop()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .priority(Priority.NORMAL)
                    .error(ERROR)
                    //当url为空时，显示图片
                    .fallback(ERROR).listener(new RequestListener<Object, GlideDrawable>() {
                @Override
                public boolean onException(Exception e, Object model, Target<GlideDrawable> target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(GlideDrawable resource, Object model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    // 获取gif动画时长
                    GifDrawable drawable = (GifDrawable) resource;
                    GifDecoder decoder = drawable.getDecoder();
                    long duration = 0;
                    for (int i = 0; i < drawable.getFrameCount(); i++) {
                        duration += decoder.getDelay(i);
                    }
                    return false;
                }
            }).into(new GlideDrawableImageViewTarget(view, count));
        }
    }


    /**
     * 高斯模糊图片
     * 模糊radius不能超过25.0f
     *
     * @param context context
     * @param src     String/uri/url/drawable/file/integer/byte[]/object
     * @param view    ImageView
     * @param cache   是否缓存
     */

    public void loadBlurPic(final Context context, Object src, ImageView view, float radius, boolean cache) {
        if (context == null || view == null) {
            return;
        }
        if (cache) {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new BlurTransformation(context, radius))
                    /*.placeholder(PLACEHOLDER)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)*/
                    .into(view);
        } else {
            Glide.with(context)
                    .load(src)
                    .listener(bitmapListener)
                    .dontAnimate()
                    //.animate(R.anim.alpha_in)
                    // 跳过内存缓存
                    .skipMemoryCache(true)
                    // 不在disk硬盘中缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new BlurTransformation(context, radius))
                   /* .placeholder(PLACEHOLDER)
                    .error(ERROR_CIRCLE)
                    //当url为空时，显示图片
                    .fallback(ERROR_CIRCLE)*/
                    .into(view);

        }
    }

    /**
     * 获取imageview的图片，获取Bitmap
     *
     * @param imageView ImageView
     */
    public Bitmap getBitmapByImageView(ImageView imageView) {
        // 从ImageView得到Bitmap对象
        return ((GlideBitmapDrawable) imageView.getDrawable()).getBitmap();
    }

    /**
     * 获取imageview的图片，并且转化为可传递的string
     *
     * @param imageView ImageView
     */
    public String getStringByImageView(ImageView imageView) {

        // 从ImageView得到Bitmap对象
        Bitmap bitmap = ((GlideBitmapDrawable) imageView.getDrawable()).getBitmap();
        // 把Bitmap转码成字符串
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 50, baos);
        return new String(Base64.encode(baos.toByteArray(), 0));
    }


    /**
     * Bitmap转化为可传递的string
     *
     * @param bitmap Bitmap
     */
    public String getImageStringByBitmap(Bitmap bitmap) {
        // 把Bitmap转码成字符串
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 50, baos);
        return new String(Base64.encode(baos.toByteArray(), 0));
    }

    /**
     * base64转byte[]
     *
     * @param imageBase64 String
     */
    public byte[] getArray64(String imageBase64) {
        byte[] byte64 = Base64.decode(imageBase64, 0);
        ByteArrayInputStream bais = new ByteArrayInputStream(byte64);
        Bitmap bitmap = BitmapFactory.decodeStream(bais);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

        return baos.toByteArray();
    }

    /**
     * 取消加载所有正要加载进这个View的资源,并释放所有已加载至这个View的资源
     */
    public void clearView(final ImageView view) {
        try {
            if (Looper.myLooper() != Looper.getMainLooper()) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Glide.clear(view);
                    }
                });
            } else {
                Glide.clear(view);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除图片磁盘缓存，只能在子线程调用
     */
    public void clearImageDiskCache(final Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                Observable.just(0).subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer value) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        Glide.get(context).clearDiskCache();

                    }
                });

            } else {
                Glide.get(context).clearDiskCache();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除图片内存缓存,只能在主线程执行
     */
    public void clearImageMemoryCache(Context context) {
        try {
            //只能在主线程执行
            if (Looper.myLooper() == Looper.getMainLooper()) {
                Glide.get(context).clearMemory();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除图片所有缓存
     * todo
     */
    public void clearImageAllCache(Context context) {
        clearImageDiskCache(context);
        clearImageMemoryCache(context);
        String imageExternalCatchDir = context.getExternalCacheDir() + ExternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR;
        deleteFolderFile(imageExternalCatchDir, true);
    }

    /**
     * 获取Glide造成的缓存大小
     *
     * @return CacheSize
     */
    public String getCacheSize(Context context) {
        try {
            return getFormatSize(getFolderSize(new File(context.getCacheDir() + "/" + InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取指定文件夹内所有文件大小的和
     *
     * @param file file
     * @return size
     * @throws Exception ex
     */
    public long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 删除指定目录下的文件，这里用于缓存的删除
     *
     * @param filePath       filePath
     * @param deleteThisPath deleteThisPath
     */
    private void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {
                    File[] files = file.listFiles();
                    for (File file1 : files) {
                        deleteFolderFile(file1.getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {
                        file.delete();
                    } else {
                        if (file.listFiles().length == 0) {
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 格式化单位
     *
     * @param size size
     * @return size
     */
    private String getFormatSize(double size) {

        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);

        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }

    private FutureTarget<File> future;
    private String path = null;

    /**
     * 获得图片缓存路径
     *
     * @param imgUrl  图片来源
     * @param context context
     *                <p>
     *                todo
     */
    public synchronized String getImagePath(final Context context, final String imgUrl) {


        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                Observable.just(0).subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer value) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        future = Glide.with(context)
                                .load(imgUrl)
                                .downloadOnly(100, 100);

                        File cacheFile = null;
                        try {
                            cacheFile = future.get();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                        if (cacheFile != null) {
                            path = cacheFile.getAbsolutePath();
                        }
                    }
                });

            } else {
                future = Glide.with(context)
                        .load(imgUrl)
                        .downloadOnly(0, 500);

                File cacheFile = future.get();
                path = cacheFile.getAbsolutePath();
            }


        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        Log.i("PictureManager", "getImagePath: " + path);
        return path;
    }


    /**
     * 高斯模糊处理
     */
    private class BlurTransformation extends BitmapTransformation {

        private final String ID = "BlurTransformation";

        private final float DEFAULT_RADIUS = 25.0f;
        private final float MAX_RADIUS = 25.0f;
        private final float DEFAULT_SAMPLING = 1.0f;

        private Context mContext;
        private float mSampling = DEFAULT_SAMPLING;
        private float mRadius;
        private int mColor = Color.TRANSPARENT;


        /**
         * @param context Context
         * @param radius  模糊程度
         * @param color   The color filter for blurring.
         */
        public BlurTransformation(Context context, @FloatRange(from = 0.0f) float radius, int color) {
            super(context);
            mContext = context;
            if (radius > MAX_RADIUS) {
                mSampling = radius / 25.0f;
                mRadius = MAX_RADIUS;
            } else {
                mRadius = radius;
            }
            mColor = color;
        }

        /**
         * @param context Context
         * @param radius  The blur's radius.
         */
        private BlurTransformation(Context context, @FloatRange(from = 0.0f) float radius) {
            this(context, radius, Color.TRANSPARENT);
        }

        public BlurTransformation(Context context) {
            this(context, 25.0f);
        }

        /**
         * Transforms the given {@link Bitmap} based on the given dimensions and returns the transformed
         * result.
         * <p/>
         * <p>
         * The provided Bitmap, toTransform, should not be recycled or returned to the pool. Glide will automatically
         * recycle and/or reuse toTransform if the transformation returns a different Bitmap. Similarly implementations
         * should never recycle or return Bitmaps that are returned as the result of this method. Recycling or returning
         * the provided and/or the returned Bitmap to the pool will lead to a variety of runtime exceptions and drawing
         * errors. See #408 for an example. If the implementation obtains and discards intermediate Bitmaps, they may
         * safely be returned to the BitmapPool and/or recycled.
         * </p>
         * <p/>
         * <p>
         * outWidth and outHeight will never be {@link Target#SIZE_ORIGINAL}, this
         * class converts them to be the size of the Bitmap we're going to transform before calling this method.
         * </p>
         *
         * @param pool        A {@link BitmapPool} that can be used to obtain and
         *                    return intermediate {@link Bitmap}s used in this transformation. For every
         *                    {@link Bitmap} obtained from the pool during this transformation, a
         *                    {@link Bitmap} must also be returned.
         * @param toTransform The {@link Bitmap} to transform.
         * @param outWidth    The ideal width of the transformed bitmap (the transformed width does not need to match exactly).
         * @param outHeight   The ideal height of the transformed bitmap (the transformed heightdoes not need to match
         */
        @Override
        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            boolean needScaled = mSampling == DEFAULT_SAMPLING;
            int originWidth = toTransform.getWidth();
            int originHeight = toTransform.getHeight();
            int width, height;
            if (needScaled) {
                width = originWidth;
                height = originHeight;
            } else {
                width = (int) (originWidth / mSampling);
                height = (int) (originHeight / mSampling);
            }
            //find a re-use bitmap
            Bitmap bitmap = pool.get(width, height, Bitmap.Config.ARGB_8888);
            if (bitmap == null) {
                bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            }

            Canvas canvas = new Canvas(bitmap);
            if (mSampling != DEFAULT_SAMPLING) {
                canvas.scale(1 / mSampling, 1 / mSampling);
            }
            Paint paint = new Paint();
            paint.setFlags(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);
            PorterDuffColorFilter filter =
                    new PorterDuffColorFilter(mColor, PorterDuff.Mode.SRC_ATOP);
            paint.setColorFilter(filter);
            canvas.drawBitmap(toTransform, 0, 0, paint);
// TIPS: Glide will take care of returning our original Bitmap to the BitmapPool for us,
// we needn't to recycle it.
//        toTransform.recycle();  <--- Just for tips. by Ligboy

            RenderScript rs = RenderScript.create(mContext);
            Allocation input = Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE,
                    Allocation.USAGE_SCRIPT);
            Allocation output = Allocation.createTyped(rs, input.getType());
            ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));

            blur.setInput(input);
            blur.setRadius(mRadius);
            blur.forEach(output);
            output.copyTo(bitmap);

            rs.destroy();

            if (needScaled) {
                return bitmap;
            } else {
                Bitmap scaled = Bitmap.createScaledBitmap(bitmap, originWidth, originHeight, true);
                bitmap.recycle();
                return scaled;
            }
        }

        /**
         * A method to get a unique identifier for this particular transformation that can be used as part of a cache key.
         * The fully qualified class name for this class is appropriate if written out, but getClass().getName() is not
         * because the name may be changed by proguard.
         * <p/>
         * <p>
         * If this transformation does not affect the data that will be stored in cache, returning an empty string here
         * is acceptable.
         * </p>
         *
         * @return A string that uniquely identifies this transformation.
         */
        @Override
        public String getId() {
            return ID + '-' + mRadius + '-' + mColor;
        }
    }


}

